﻿using System;
using System.Html.DOM.CSS;

namespace RexToy.UI.Controls
{
    public class InPlacePopup : Container
    {
        private DomNode _backNode;

        public InPlacePopup()
        {
            this.__dragEventBubble = false;
            this.__palette = Palette.A;
            this.__domNode = RexToy.UI.Controls.DomNode.Create(new DomNodeCreateOptions()
            {
                tag = Tag.Div,
                hashName = "container",
                className = "ui-inplace-popup ui-overlay-shadow ui-corner-all ui-inplace-popup-hidden ui-body-a"
            });

            this._backNode = RexToy.UI.Controls.DomNode.Create(new DomNodeCreateOptions()
            {
                tag = Tag.Div,
                className = "ui-selectmenu-screen ui-screen-hidden"
            });
            this._backNode.AttachEvent(DomEvent.OnClick, new Action(this.ClickOutside).Bind(this));
        }

        private void ClickOutside()
        {
            this.Close();
        }

        public void Show(Point position)
        {
            var x = position.X;
            var w = this.GetSize().Width;
            if (x + w > RexToy.UI.Global.Window.GetSize().Width)
            {
                x = RexToy.UI.Global.Window.GetSize().Width - w;
            }
            var y = position.Y;
            var h = this.GetSize().Height;
            if (y + h > RexToy.UI.Global.Window.GetSize().Height)
            {
                y = RexToy.UI.Global.Window.GetSize().Height - h;
            }

            this.__domNode.RemoveClass("ui-inplace-popup-hidden");
            var style = this.__domNode.GetStyle();
            style.Left = x + "px";
            style.Top = y + "px";

            RexToy.UI.Global.Window.GetDocumentBody().AppendChild(this._backNode);
            this._backNode.RemoveClass("ui-screen-hidden");
        }

        public void Close()
        {
            var style = this.__domNode.GetStyle();
            style.Left = null;
            style.Top = null;
            this.__domNode.AppendClass("ui-inplace-popup-hidden");

            RexToy.UI.Global.Window.GetDocumentBody().RemoveChild(this._backNode);
            this._backNode.AppendClass("ui-screen-hidden");
        }

        public override void Destroy()
        {
            this.Super();
            RexToy.UI.Global.Window.GetDocumentBody().RemoveChild(this._backNode);
        }

        public override Palette Palette
        {
            get
            {
                return __palette;
            }
            set
            {
                var template = "ui-body-{0}";
                this.__domNode.ReplaceClass(StringExt.Format(template, this.__palette), StringExt.Format(template, value));
                this.__palette = value;
            }
        }
    }
}
